package org.collector.baseoper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.http.client.HttpClient;
import org.collector.data.controllerdata.SiteOfProxySnapshot;
import org.collector.data.controllerdata.SiteOfProxyStatu;
import org.collector.data.controllerdata.SumSiteOfProxySnapshot;
import org.collector.util.HttpClientTools;

public class ParamListIndex {
	private String strUrl;
	private ArrayList<ParamManage> paramList;
	private final static int UPDATELIST_THRESHOLD = 15;
	private int updatelist_threshold;
	private AtomicInteger usetimes;
	private HttpClient httpClient;
	private HashMap<HttpClient,HttpClientStatu> clientWithStatu;
	
	public ParamListIndex(String url,HashMap<HttpClient,HttpClientStatu> clientWithStatu,int updatelist_threshold){
		this.strUrl = url;
		paramList = new ArrayList<ParamManage>();
		this.clientWithStatu = clientWithStatu;
		usetimes = new AtomicInteger(0);
		httpClient = null;
		this.updatelist_threshold = updatelist_threshold;
	}
	public ParamListIndex(String url,HashMap<HttpClient,HttpClientStatu> clientWithStatu){
		this(url,clientWithStatu,UPDATELIST_THRESHOLD);
	}
	private void fillParamManageList(){
		synchronized(paramList){
			paramList.clear();
			synchronized(clientWithStatu){
				for(HttpClient client: clientWithStatu.keySet()){
					HttpClientStatu statu = clientWithStatu.get(client);
					paramList.add(new ParamManage(client,statu.getSiteOfProxyStatu(this.strUrl)));
				}
			}
			SumSiteOfProxySnapshot ssps = new SumSiteOfProxySnapshot();
			for(ParamManage pm: paramList){
				ssps.addSiteOfProxySnapshot(pm.getSiteOfProxySnapshot());
			}
			float score = 0;
			for(ParamManage pm: paramList){
				float tmpscore = HttpClientTools.computeHttpPriority(pm.getSiteOfProxySnapshot(),ssps);
				if(tmpscore >= score){
					score = tmpscore;
					httpClient = pm.getHttpClient();
				}
			}
		}
	}
	public HttpClient getHttpClient(){
		synchronized(paramList){
			if(usetimes.getAndIncrement() % updatelist_threshold == 0){
				fillParamManageList();
			}
			return httpClient;
		}
	}
	private final static class ParamManage {
		private HttpClient httpClient;
		private SiteOfProxySnapshot siteOfProxySnapshot;
		public ParamManage(HttpClient httpClient,SiteOfProxyStatu statu){
			this.httpClient = httpClient;
			this.siteOfProxySnapshot = new SiteOfProxySnapshot(statu);
		}
		public HttpClient getHttpClient() {
			return httpClient;
		}
		public SiteOfProxySnapshot getSiteOfProxySnapshot() {
			return siteOfProxySnapshot;
		}
	};
}
